package com.hongxun.design.activitys;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.LogEditAdapter;
import com.hongxun.design.bean.LogBean;
import com.hongxun.design.bean.LogListBean;
import com.hongxun.design.bean.LogProjectBean;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.ui.voicerecorder.VoiceRecorder;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.TimeUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.soundUtil.UPlayer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zerdoor_pc on 2016/6/24.
 * 日志填报
 */
public class LogEditActivity extends BaseActivity implements HeadSecond, View.OnClickListener {
    SwipeRefreshListView logedit_list;
    private Handler dataHandler, logListHandler;
    private Handler assessedHandler;
    List<LogProjectBean> logBeans;
    LogEditAdapter adapter;

    String voice_url = "";//录音后url;
    String dayjson = "";
    boolean isEdit = true;
    LogBean logBean;

    // LoadingDialog dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logedit);
//        dialog = new LoadingDialog(this);
//        dialog.show();
//        dialog.setText("正在获取日志信息！");
//        addLogListHandler();
//        getHttp();
        findBar();
        findView();

    }

    @Override
    public void findBar() {
        Bundle bundle = getIntent().getExtras();
        dayjson = bundle.getString(MString.CODE);
        int viewcode = View.VISIBLE;
        if (dayjson == null || dayjson.length() == 0) {
            isEdit = true;
        } else {
            logBean = FastJsonUtil.JsonToGetLog(dayjson);
//            if (logBean.getVoice_remark().length() > 0) {
//                String[] tar = logBean.getVoice_remark().split("/");
//                String name = "";
//                if (tar != null && tar.length > 1) {
//                    name = tar[tar.length - 1];
//                } else {
//                    name = System.currentTimeMillis() + ".amr";
//                }
//                voice_url=MyApp.File.getCachaVoicePath() + name;
//                logBean.setVoice_remark(MyApp.getHttpVoice(logBean.getVoice_remark(), voice_url));
//                logBean.setVoice_remark(voice_url);
//
//            }

            if (logBean.getCreate_time().contains(TimeUtil.getTime())) {
                viewcode = View.GONE;
                isEdit = false;
            } else {
                isEdit = true;
            }

        }
        MyLog.L(MString.SUCCESSED + " isEdit=" + isEdit);
        MyLog.L(MString.SUCCESSED + " dayjson=" + dayjson);

        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.logfill_layout);
        headsecond_layout.initHeadPanel(DataUtil.getsecondbean(MString.Save, viewcode, R.color.bar_right, ListenerSet.back, "日志填报 " + TimeUtil.getTime(), R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        headsecond_layout.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                save();
            }
        });

    }

    /**
     * 获取当天数据
     **/
    private void getHttp() {
        MyApp.HTTP.LogList(logListHandler, HttpStringUtil.SUCCESSED, TimeUtil.getTime(), TimeUtil.getTime(), "", 0, 10);
    }

    List<LogBean> beanList = null;

    private void addLogListHandler() {
//        logListHandler=new Handler(){
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                switch (msg.what){
//                    case HttpStringUtil.SUCCESSED:
//                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
//
//                            if (beanList == null) {
//                                beanList = FastJsonUtil.JsonToGetLogList((String) msg.obj);
//                            } else {
//                                beanList.clear();
//                                beanList.addAll(FastJsonUtil.JsonToGetLogList((String) msg.obj));
//                            }
//                            logListHandler.sendEmptyMessage(1);
//                        } else {
//                         error(FastJsonUtil.JsonToCheck_String((String) msg.obj));
//                        }
//                        break;
//                    case 1:
//                        success("操作成功！");
//                        if (logBeans == null) {
//                            logBeans = new ArrayList<>();
//                        }
//                        logBeans.clear();
//                        if (beanList.size()>0){
//                            dayjson= JSON.toJSONString(beanList.get(0));
//                            logBeans.addAll(beanList.get(0).getProject());
//                        }
//                        findBar();
//                        findView();
//
//                        break;
//                    case HttpStringUtil.ERROR:
//                        error((String) msg.obj);
//                        break;
//                }
//            }
//        };
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    TextView vremarks, return_button, play;
    LinearLayout play_button;
    EditText wordsremarks;
    RelativeLayout log_mid;

    @Override
    protected void findView() {
        super.findView();
        logedit_list = (SwipeRefreshListView) findViewById(R.id.logedit_list);//项目列表
        wordsremarks = (EditText) findViewById(R.id.log_wordsremarks);//文字备注输入框

        vremarks = (TextView) findViewById(R.id.log_vremarks);//语音录入框
        play_button = (LinearLayout) findViewById(R.id.log_play_button);//显示播放按钮
        return_button = (TextView) findViewById(R.id.log_return_button);//重录按钮
        log_mid = (RelativeLayout) findViewById(R.id.log_mid);
        play = (TextView) findViewById(R.id.log_play);//播放按钮
        //return_button.setOnClickListener(this);
        return_button.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                MyLog.L(MyApp.AppName + "进入：" + motionEvent);
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    btn_vocie = true;
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    btn_vocie = false;
                }
                return false;
            }

        });
        play.setOnClickListener(this);
        addHandler();
        inItList();
        //addVoiceClick();
        addVoiceInit();//语音监听器
        addAssessedHandler();//保存监听
    }

    private void inItList() {
        logedit_list.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                if (isEdit) {
                Refresh();
//                } else {
//                    logedit_list.setRefreshing(false);
//                }
            }
        });
//        if (isEdit) {
        Refresh();
//        } else {
//            //logBean;
//            if (logBeans == null) {
//                logBeans = new ArrayList<>();
//            }
//            logBeans.clear();
//            logBeans.addAll(logBean.getProject());
//            dataHandler.sendEmptyMessage(1);
//        }

    }

    private void addVoiceClick() {
        /*初始状态**/
        if (isEdit) {
            /**设置播放按钮样式**/
            SetTypeface.set(vremarks, IconSourse.Recording);//设置对应字体与文字
            SpannableString styledText2 = new SpannableString(" 语音备注");
            styledText2.setSpan(new TextAppearanceSpan(this, R.style.style0), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            vremarks.append(styledText2);

            SetTypeface.set(return_button, IconSourse.Recording);//设置对应字体与文字
            SpannableString styledText1 = new SpannableString(" 重录");
            styledText1.setSpan(new TextAppearanceSpan(this, R.style.style0), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            return_button.append(styledText1);

            update(voice_url);
            vremarks.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    MyLog.L(MyApp.AppName + "进入：" + motionEvent);
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        btn_vocie = true;
                    } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                        btn_vocie = false;
                    }
                    return false;
                }

            });
        } else {
            log_mid.setVisibility(View.GONE);
            return_button.setVisibility(View.GONE);
            wordsremarks.setText(logBean.getCharacters_remark());
            wordsremarks.setEnabled(false);
            update(logBean.getVoice_remark());
        }
    }

    /**
     * 刷新按钮*
     */
    private void update(String s) {
        SetTypeface.set(play, IconSourse.PLAY);//设置对应字体与文字
        if (s.length() == 0 && isEdit) {
            vremarks.setVisibility(View.VISIBLE);
            play_button.setVisibility(View.GONE);
        } else {
            vremarks.setVisibility(View.GONE);
            play_button.setVisibility(View.VISIBLE);
            double length = -1;
            if (s.length() > 0) {
                if (UPlayer.getIntence(s).mPlayer != null) {
                    length = ((double) UPlayer.getIntence(s).getDuration() / (double) 1000);
                }
            }
            String value = length + "";
            if (length <= 0) value = "播放";
            SpannableString styledText = new SpannableString(value);
            styledText.setSpan(new TextAppearanceSpan(this, R.style.style0), 0, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            play.append(styledText);
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.log_return_button://重录
                voice_url = "";
                update(voice_url);
                break;
            case R.id.log_play://播放
                if (voice_url.length() != 0) {
                    UPlayer.getIntence(voice_url).start();
                } else {
                    ToastShow.showShort(this, "播放路径不存在！");
                    SetTypeface.set(play, IconSourse.PLAY);//设置对应字体与文字
                    String value = "0.00";
                    SpannableString styledText = new SpannableString(value);
                    styledText.setSpan(new TextAppearanceSpan(this, R.style.style0), 0, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    play.append(styledText);
                    voice_url = "";
                    //update(voice_url);
                }
                break;
        }
    }

    /**
     * 今日项目信息刷新*
     */
    private void Refresh() {
        MyApp.HTTP.TodayProSum(dataHandler, HttpStringUtil.SUCCESSED);
//        dataHandler.sendEmptyMessage(1);
    }

    /**
     * 今日项目信息刷新*
     */
    private void save() {
        File file = new File(voice_url);
        if (file.exists() && file.length() > 0) {
            MyApp.HTTP.sendFile(proHandler, HttpStringUtil.SUCCESSED, file, MString.PROJECT_RADIO);
        } else {
            MyApp.HTTP.AssessedLog(assessedHandler, HttpStringUtil.SUCCESSED, logBeans, "", wordsremarks.getText().toString());
        }

    }

    private void addAssessedHandler() {
        assessedHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            ToastShow.showShort(mActivity, "保存成功！");
                            mActivity.onBackPressed();
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                }
            }
        };
    }


    /**
     * 今日项目信息接收器*
     */
    private void addHandler() {
        dataHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (logBeans == null) {
                                logBeans = new ArrayList<>();
                            } else {
                                logBeans.clear();
                            }
                            LogListBean bean = FastJsonUtil.JsonToGetTodayProSum((String) msg.obj);
                            if (bean == null) bean = new LogListBean();
                            logBeans.addAll(bean.getTodayProSum());
                            if (logBean == null) logBean = new LogBean();
                            logBean.setCharacters_remark(bean.getCharacters_remark());
                            logBean.setVoice_remark(bean.getVoice_remark());
                            if (logBean.getVoice_remark().length() > 0) {
                                String[] tar = logBean.getVoice_remark().split("/");
                                String name = "";
                                if (tar != null && tar.length > 1) {
                                    name = tar[tar.length - 1];
                                } else {
                                    name = System.currentTimeMillis() + ".amr";
                                }
                                voice_url = MyApp.File.getCachaVoicePath() + name;
                                voice_url=MyApp.getHttpVoice(logBean.getVoice_remark(), voice_url);
                                logBean.setVoice_remark(voice_url);
                                //logBean.setVoice_remark(voice_url);

                            }
                            int viewcode = View.VISIBLE;
                            HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.logfill_layout);
                            if (bean == null || (bean.getCharacters_remark().length() == 0 && bean.getVoice_remark().length() == 0)) {
                                isEdit = true;
                            } else {
                                viewcode = View.GONE;
                                isEdit = false;
                            }
                            headsecond_layout.initHeadPanel(DataUtil.getsecondbean(MString.Save, viewcode, R.color.bar_right, ListenerSet.back, "日志填报 " + TimeUtil.getTime(), R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));

                            dataHandler.sendEmptyMessage(1);
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                            logedit_list.setRefreshing(false);
                        }
                        break;

                    case 1:
                        addVoiceClick();
                        if (adapter == null) {
                            adapter = new LogEditAdapter(mActivity, logBeans);
                            logedit_list.setAdapter(adapter, "今日没有项目日志");

                        } else {
                            logedit_list.update("今日没有项目日志");
                            logedit_list.setRefreshing(false);

                        }
                        break;

                    case HttpStringUtil.ERROR:
                        logedit_list.setRefreshing(false);
                        break;
                }
            }
        };
    }


    /**
     * 语音相关属性*
     */

    private void addVoiceInit() {
        setHandler();//录音音量handler
        findViewOfVoice();//录音控件初始化
        addProHandler();//加载语音上传监听器
    }

    private LinearLayout voice_rcd_hint_loading,
            voice_rcd_hint_tooshort;
    private RelativeLayout voice_rcd_hint_rcding;
    private View rcChat_popup;
    VoiceRecorder voiceRecorder;
    private LinearLayout del_re, my_voice;
    private ImageView volume;
    Handler handler;
    public static boolean btn_vocie = false;
    private int flag = 1;
    private long startVoiceT, endVoiceT;
    private boolean isShosrt = false;
    private String openid;
    private int[] micImages = new int[]{R.mipmap.amp1,
            R.mipmap.amp2,
            R.mipmap.amp3,
            R.mipmap.amp4,
            R.mipmap.amp5,
            R.mipmap.amp6,
            R.mipmap.amp7,
    };
    private Handler proHandler;
    private final int SPEECH = 1;
    float time;

    private void findViewOfVoice() {
        volume = (ImageView) this.findViewById(R.id.volume);//音量
        voice_rcd_hint_rcding = (RelativeLayout) this
                .findViewById(R.id.voice_rcd_hint_rcding);
        voice_rcd_hint_loading = (LinearLayout) this
                .findViewById(R.id.voice_rcd_hint_loading);
        voice_rcd_hint_tooshort = (LinearLayout) this
                .findViewById(R.id.voice_rcd_hint_tooshort);
        rcChat_popup = this.findViewById(R.id.rcChat_popup);
        del_re = (LinearLayout) this.findViewById(R.id.del_re);//取消
        my_voice = (LinearLayout) this.findViewById(R.id.my_voice);//录制
        voiceRecorder = new VoiceRecorder(handler);
        openid = "";
    }

    /**
     * 录音handler*
     */
    private void setHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                volume.setImageResource(micImages[msg.what / 2]);
            }
        };
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        MyLog.L("listdatalistdatalistdata:onTouch3");
        MyLog.L(MyApp.AppName + "进入：" + event);
        if (!Environment.getExternalStorageDirectory().exists()) {
            ToastShow.showShort(this, "No SDCard");
            return false;
        }
        if (btn_vocie) {
            int[] location = new int[2];
            //if (view!=null)view.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标
            int btn_rc_Y = location[1];
            int btn_rc_X = location[0];
            int[] del_location = new int[2];
            del_re.getLocationInWindow(del_location);
            int del_Y = del_location[1];
            int del_x = del_location[0];
            if (event.getAction() == MotionEvent.ACTION_DOWN && flag == 1) {
                if (!Environment.getExternalStorageDirectory().exists()) {
                    ToastShow.showShort(this, "No SDCard");
                    return false;
                }
                if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {
                    //判断手势按下的位置是否是语音录制按钮的范围内
                    //mBtnRcd.setBackgroundResource(R.drawable.radius_social_chat_voice);//语音录制开始
                    //mBtnRcd.setText("松开发送");
                    rcChat_popup.setVisibility(View.VISIBLE);
                    voice_rcd_hint_loading.setVisibility(View.VISIBLE);
                    voice_rcd_hint_rcding.setVisibility(View.GONE);
                    voice_rcd_hint_tooshort.setVisibility(View.GONE);
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            if (!isShosrt) {
                                voice_rcd_hint_loading.setVisibility(View.GONE);
                                voice_rcd_hint_rcding
                                        .setVisibility(View.VISIBLE);
                            }
                        }
                    }, 300);
                    del_re.setVisibility(View.GONE);
                    my_voice.setVisibility(View.VISIBLE);
                    startVoiceT = System.currentTimeMillis();

                    try {
                        voiceRecorder.startRecording(null, openid, getApplicationContext());
                    } catch (Exception e) {
                        if (voiceRecorder != null)
                            voiceRecorder.discardRecording();
                    }
                    flag = 2;
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP && flag == 2) {//松开手势时执行录制完成
                //mBtnRcd.setBackgroundResource(R.drawable.radius_social_chat_voice_none);
                //mBtnRcd.setText("按住说话");
                if (del_re.getVisibility() == View.VISIBLE) {
                    rcChat_popup.setVisibility(View.GONE);
                    del_re.setVisibility(View.GONE);
                    my_voice.setVisibility(View.VISIBLE);
                    flag = 1;
                    if (voiceRecorder != null) {
                        File file = new File(voiceRecorder.getVoiceFilePath());
                        voiceRecorder.discardRecording();
                        if (file.exists()) {
                            file.delete();
                        }
                    }
                } else {
                    voice_rcd_hint_rcding.setVisibility(View.GONE);
                    endVoiceT = System.currentTimeMillis();// SystemClock.currentThreadTimeMillis();
                    flag = 1;
                    time = (float) ((endVoiceT - startVoiceT) / 1000);
                    if (time < 1) {

                        //Log.i("", "环信===时间短");
                        isShosrt = true;
                        voice_rcd_hint_loading.setVisibility(View.GONE);
                        voice_rcd_hint_rcding.setVisibility(View.GONE);
                        voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
                        if (voiceRecorder != null) {
                            File file = new File(voiceRecorder.getVoiceFilePath());
                            voiceRecorder.discardRecording();
                            if (file.exists()) {
                                file.delete();
                            }
                        }
                        handler.postDelayed(new Runnable() {
                            public void run() {
                                voice_rcd_hint_tooshort
                                        .setVisibility(View.GONE);
                                rcChat_popup.setVisibility(View.GONE);

                                isShosrt = false;
                            }
                        }, 100);
                        btn_vocie = false;
                        //Log.i("", "环信===时间短返回");
                        return false;
                    }


                    int length = voiceRecorder.stopRecoding();
                    if (length > 0) {

                        btn_vocie = false;
                        voice_url = voiceRecorder.getVoiceFilePath();

                        if (voice_url.length() > 0) {
                            String[] tar = voice_url.split("/");
                            String name = "";
                            if (tar != null && tar.length > 1) {
                                name = tar[tar.length - 1];
                            } else {
                                name = System.currentTimeMillis() + ".amr";
                            }
                            voice_url = MyApp.getHttpVoice(voice_url, MyApp.File.getCachaVoicePath() + name);

                        }
                        update(voice_url);
                    }
                }
            }
            if (event.getY() < btn_rc_Y) {//手势按下的位置不在语音录制按钮的范围内
                del_re.setVisibility(View.VISIBLE);
                my_voice.setVisibility(View.GONE);
                btn_vocie = false;
                if (event.getY() >= del_Y
                        && event.getY() <= del_Y + del_re.getHeight()
                        && event.getX() >= del_x
                        && event.getX() <= del_x + del_re.getWidth()) {
                }

                if (voiceRecorder != null)
                    voiceRecorder.discardRecording();
            } else {
                del_re.setVisibility(View.GONE);
                my_voice.setVisibility(View.VISIBLE);

            }
        }
        return super.onTouchEvent(event);
    }


    /**
     * 上传语音*
     */
    private void addProHandler() {
        proHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            String path = FastJsonUtil.JsonToPath((String) msg.obj);
                            if (path != null && path.length() > 0) {
                                MyApp.HTTP.AssessedLog(assessedHandler, HttpStringUtil.SUCCESSED, logBeans, path, wordsremarks.getText().toString());
                            }
//                            else {
//                                voice_url = "";
//                            }
//
//                            if (voice_url.length() > 0) {
//                                String[] tar = voice_url.split("/");
//                                String name = "";
//                                if (tar != null && tar.length > 1) {
//                                    name = tar[tar.length - 1];
//                                } else {
//                                    name = System.currentTimeMillis() + ".amr";
//                                }
//                                voice_url = MyApp.getHttpVoice(voice_url, MyApp.File.getCachaVoicePath() + name);
//
//                            }
//                            update(voice_url);
                        }
                        break;
                    case SPEECH:
                        break;
                    case HttpStringUtil.ERROR:
                        break;

                }
            }
        };
    }


    @Override
    public void onDestroy() {

        logedit_list.destory(logedit_list);
        super.onDestroy();
    }


//    private void success(String text) {
//        if (dialog != null && dialog.isShowing()) {
//            dialog.setText(text);
//            closeDialog();
//        }
//    }
//
//    private void error(String text) {
//        if (dialog != null && dialog.isShowing()) {
//            dialog.setText(text);
//            closeDialog();
//        }
//
//    }
//
//    private void closeDialog() {
//        (new Handler()).postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if (dialog != null && dialog.isShowing()) {
//                    try {
//                        dialog.dismiss();
//                        dialog = null;
//                    } catch (Exception e) {
//                    }
//                }
//            }
//        }, 1000);
//
//    }
}
